<template>
  <MainLayout>
    <div class="submissions-page">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-left">
          <h2>提交记录</h2>
          <p class="page-description">
            查看您的所有提交记录和评测结果
            <span v-if="pollingEnabled" class="realtime-indicator">
              <el-icon class="pulse-icon"><VideoPlay /></el-icon>
              实时更新中
            </span>
          </p>
        </div>
        <div class="header-right">
          <el-button-group>
            <el-button @click="refreshSubmissions">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button 
              @click="toggleRealTimeUpdates" 
              :type="pollingEnabled ? 'success' : 'default'"
              :icon="pollingEnabled ? 'VideoPause' : 'VideoPlay'"
            >
              {{ pollingEnabled ? '关闭实时' : '开启实时' }}
            </el-button>
            <el-button @click="exportSubmissions">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchQuery"
              placeholder="搜索题目或作业..."
              prefix-icon="Search"
              clearable
              @input="filterSubmissions"
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="statusFilter" placeholder="提交状态" clearable @change="filterSubmissions">
              <el-option label="全部状态" value="" />
              <el-option label="通过" value="AC" />
              <el-option label="答案错误" value="WA" />
              <el-option label="超时" value="TLE" />
              <el-option label="运行时错误" value="RE" />
              <el-option label="编译错误" value="CE" />
              <el-option label="评测中" value="pending" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="languageFilter" placeholder="编程语言" clearable @change="filterSubmissions">
              <el-option label="全部语言" value="" />
              <el-option label="Python" value="python" />
              <el-option label="C++" value="cpp" />
              <el-option label="Java" value="java" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="filterSubmissions"
            />
          </el-col>
        </el-row>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-info">
                  <p class="stat-label">总提交数</p>
                  <h3 class="stat-value">{{ filteredSubmissions.length }}</h3>
                </div>
                <div class="stat-icon icon-blue">
                  <el-icon><Upload /></el-icon>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-info">
                  <p class="stat-label">通过率</p>
                  <h3 class="stat-value">{{ passRate }}%</h3>
                </div>
                <div class="stat-icon icon-green">
                  <el-icon><Check /></el-icon>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-info">
                  <p class="stat-label">平均分</p>
                  <h3 class="stat-value">{{ averageScore }}分</h3>
                </div>
                <div class="stat-icon icon-orange">
                  <el-icon><TrendCharts /></el-icon>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-info">
                  <p class="stat-label">今日提交</p>
                  <h3 class="stat-value">{{ todaySubmissions }}</h3>
                </div>
                <div class="stat-icon icon-purple">
                  <el-icon><Clock /></el-icon>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 提交列表 -->
      <el-card class="submissions-table-card">
        <el-table
          :data="filteredSubmissions"
          v-loading="loading"
          style="width: 100%"
          @row-click="viewSubmission"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="题目信息" min-width="250">
            <template #default="{ row }">
              <div class="submission-info">
                <h4 class="problem-title">{{ row.problem?.title || '未知题目' }}</h4>
                <p class="homework-title">{{ row.homework?.title || '未知作业' }}</p>
                <div class="submission-meta">
                  <el-tag v-if="row.language" :type="getLanguageTagType(row.language)" size="small">
                    {{ row.language }}
                  </el-tag>
                  <span class="submit-time">{{ formatDate(row.submit_time) }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="{ row }">
              <div class="status-info">
                <el-tag :type="getStatusTagType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
                <div v-if="row.score !== undefined" class="score-info">
                  <span class="score">{{ row.score }}/{{ row.problem?.points || 0 }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="执行信息" width="150">
            <template #default="{ row }">
              <div class="execution-info">
                <div v-if="row.execution_time !== undefined" class="execution-item">
                  <span class="label">时间:</span>
                  <span class="value">{{ row.execution_time }}ms</span>
                </div>
                <div v-if="row.memory_used !== undefined" class="execution-item">
                  <span class="label">内存:</span>
                  <span class="value">{{ row.memory_used }}MB</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click.stop="viewSubmission(row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 提交详情对话框 -->
      <el-dialog
        v-model="showDetailDialog"
        title="提交详情"
        width="900px"
        :close-on-click-modal="false"
      >
        <div v-if="selectedSubmission" class="submission-detail">
          <!-- 基本信息 -->
          <el-card class="detail-card">
            <template #header>
              <h3>基本信息</h3>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="detail-item">
                  <span class="label">题目：</span>
                  <span class="value">{{ selectedSubmission.problem?.title }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">作业：</span>
                  <span class="value">{{ selectedSubmission.homework?.title }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">提交时间：</span>
                  <span class="value">{{ formatDate(selectedSubmission.submit_time) }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="detail-item">
                  <span class="label">状态：</span>
                  <el-tag :type="getStatusTagType(selectedSubmission.status)">
                    {{ getStatusText(selectedSubmission.status) }}
                  </el-tag>
                </div>
                <div class="detail-item">
                  <span class="label">得分：</span>
                  <span class="value score">{{ selectedSubmission.score }}/{{ selectedSubmission.problem?.points }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">编程语言：</span>
                  <el-tag v-if="selectedSubmission.language" :type="getLanguageTagType(selectedSubmission.language)">
                    {{ selectedSubmission.language }}
                  </el-tag>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <!-- 执行信息 -->
          <el-card v-if="selectedSubmission.execution_time !== undefined || selectedSubmission.memory_used !== undefined" class="detail-card">
            <template #header>
              <h3>执行信息</h3>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="execution-detail">
                  <span class="label">执行时间：</span>
                  <span class="value">{{ selectedSubmission.execution_time || 0 }}ms</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="execution-detail">
                  <span class="label">内存使用：</span>
                  <span class="value">{{ selectedSubmission.memory_used || 0 }}MB</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="execution-detail">
                  <span class="label">代码长度：</span>
                  <span class="value">{{ selectedSubmission.answer?.length || 0 }}字符</span>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <!-- 错误信息 -->
          <el-card v-if="selectedSubmission.error_message" class="detail-card error-card">
            <template #header>
              <h3>错误信息</h3>
            </template>
            <pre class="error-content">{{ selectedSubmission.error_message }}</pre>
          </el-card>

          <!-- 测试结果 -->
          <el-card v-if="selectedSubmission.test_results" class="detail-card">
            <template #header>
              <h3>测试结果</h3>
            </template>
            <div class="test-results">
              <div
                v-for="(testResult, index) in parseTestResults(selectedSubmission.test_results)"
                :key="index"
                class="test-result-item"
                :class="testResult.status"
              >
                <div class="test-result-header">
                  <span>测试用例 {{ index + 1 }}</span>
                  <el-tag :type="getStatusTagType(testResult.status)" size="small">
                    {{ getStatusText(testResult.status) }}
                  </el-tag>
                </div>
                <div class="test-result-content">
                  <div class="input-output">
                    <div class="input">
                      <strong>输入：</strong>
                      <pre>{{ testResult.input }}</pre>
                    </div>
                    <div class="expected">
                      <strong>期望输出：</strong>
                      <pre>{{ testResult.expected }}</pre>
                    </div>
                    <div class="actual">
                      <strong>实际输出：</strong>
                      <pre>{{ testResult.output }}</pre>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 提交的代码 -->
          <el-card class="detail-card">
            <template #header>
              <h3>提交的代码</h3>
            </template>
            <div class="code-display">
              <pre class="code-content">{{ selectedSubmission.answer }}</pre>
            </div>
          </el-card>
        </div>
      </el-dialog>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { submissionsApi, type Submission } from '@/api/submissions'
import { ElMessage } from 'element-plus'
import { Refresh, Download, Upload, Check, TrendCharts, Clock, VideoPlay, VideoPause } from '@element-plus/icons-vue'
import MainLayout from '@/layouts/MainLayout.vue'

const router = useRouter()

const submissions = ref<Submission[]>([])
const loading = ref(false)

// 筛选和搜索
const searchQuery = ref('')
const statusFilter = ref('')
const languageFilter = ref('')
const dateRange = ref<[string, string] | null>(null)

// 详情对话框
const showDetailDialog = ref(false)
const selectedSubmission = ref<Submission | null>(null)

// 计算属性
const filteredSubmissions = computed(() => {
  return submissions.value.filter(submission => {
    const matchesSearch = !searchQuery.value || 
      (submission.problem?.title && submission.problem.title.toLowerCase().includes(searchQuery.value.toLowerCase())) ||
      (submission.homework?.title && submission.homework.title.toLowerCase().includes(searchQuery.value.toLowerCase()))
    
    const matchesStatus = !statusFilter.value || submission.status === statusFilter.value
    const matchesLanguage = !languageFilter.value || submission.language === languageFilter.value
    
    let matchesDate = true
    if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
      const submitDate = new Date(submission.submit_time)
      const startDate = new Date(dateRange.value[0])
      const endDate = new Date(dateRange.value[1])
      matchesDate = submitDate >= startDate && submitDate <= endDate
    }
    
    return matchesSearch && matchesStatus && matchesLanguage && matchesDate
  })
})

const passRate = computed(() => {
  if (submissions.value.length === 0) return 0
  const passedCount = submissions.value.filter(s => s.status === 'AC').length
  return Math.round((passedCount / submissions.value.length) * 100)
})

const averageScore = computed(() => {
  const scoredSubmissions = submissions.value.filter(s => s.score !== undefined)
  if (scoredSubmissions.length === 0) return 0
  const totalScore = scoredSubmissions.reduce((sum, s) => sum + (s.score || 0), 0)
  return Math.round(totalScore / scoredSubmissions.length)
})

const todaySubmissions = computed(() => {
  const today = new Date().toDateString()
  return submissions.value.filter(s => {
    const submitDate = new Date(s.submit_time).toDateString()
    return submitDate === today
  }).length
})

// 工具函数
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '评测中',
    AC: '通过',
    WA: '答案错误',
    RE: '运行时错误',
    TLE: '超时',
    CE: '编译错误'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'info',
    AC: 'success',
    WA: 'danger',
    RE: 'danger',
    TLE: 'warning',
    CE: 'danger'
  }
  return typeMap[status] || ''
}

const getLanguageTagType = (language: string) => {
  const typeMap: Record<string, string> = {
    python: 'success',
    cpp: 'warning',
    java: 'danger'
  }
  return typeMap[language] || 'info'
}

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

const parseTestResults = (testResultsStr: string) => {
  try {
    return JSON.parse(testResultsStr)
  } catch {
    return []
  }
}

// 方法
const loadSubmissions = async () => {
  loading.value = true
  try {
    submissions.value = await submissionsApi.getMySubmissions()
  } catch (error) {
    console.error('加载提交记录失败:', error)
    ElMessage.error('加载提交记录失败')
  } finally {
    loading.value = false
  }
}

const refreshSubmissions = () => {
  loadSubmissions()
}

// 实时更新相关
let pollingInterval: NodeJS.Timeout | null = null
let pollingEnabled = ref(false)

const startRealTimeUpdates = () => {
  if (pollingInterval) {
    clearInterval(pollingInterval)
  }
  
  pollingEnabled.value = true
  pollingInterval = setInterval(async () => {
    // 检查是否有pending状态的提交
    const hasPendingSubmissions = submissions.value.some(sub => 
      sub.status === 'pending' || sub.status === 'running' || sub.status === 'judging'
    )
    
    if (hasPendingSubmissions || pollingEnabled.value) {
      try {
        await loadSubmissions()
      } catch (error) {
        console.error('自动刷新失败:', error)
      }
    }
  }, 3000) // 每3秒轮询一次
}

const stopRealTimeUpdates = () => {
  pollingEnabled.value = false
  if (pollingInterval) {
    clearInterval(pollingInterval)
    pollingInterval = null
  }
}

const toggleRealTimeUpdates = () => {
  if (pollingEnabled.value) {
    stopRealTimeUpdates()
    ElMessage.info('已关闭实时更新')
  } else {
    startRealTimeUpdates()
    ElMessage.success('已开启实时更新')
  }
}

const filterSubmissions = () => {
  // 过滤逻辑已在computed中实现
}

const exportSubmissions = () => {
  // TODO: 实现导出功能
  ElMessage.info('导出功能开发中...')
}

const viewSubmission = (submission: Submission) => {
  selectedSubmission.value = submission
  showDetailDialog.value = true
}

onMounted(() => {
  loadSubmissions()
  // 检查是否有pending的提交，如果有则自动开启实时更新
  setTimeout(() => {
    const hasPendingSubmissions = submissions.value.some(sub => 
      sub.status === 'pending' || sub.status === 'running' || sub.status === 'judging'
    )
    if (hasPendingSubmissions) {
      startRealTimeUpdates()
    }
  }, 1000)
})

onUnmounted(() => {
  stopRealTimeUpdates()
})
</script>

<style scoped lang="scss">
.submissions-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;

  .header-left {
    h2 {
      margin: 0 0 8px 0;
      color: #2c3e50;
      font-size: 1.8rem;
      font-weight: bold;
    }

    .page-description {
      margin: 0;
      color: #7f8c8d;
      font-size: 1rem;
      
      .realtime-indicator {
        margin-left: 12px;
        color: #28a745;
        font-weight: 500;
        display: inline-flex;
        align-items: center;
        gap: 4px;
        
        .pulse-icon {
          animation: pulse 2s infinite;
        }
      }
    }
  }

  .header-right {
    .el-button-group {
      .el-button {
        display: flex;
        align-items: center;
        gap: 6px;
      }
    }
  }
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

/* 统计卡片 */
.stats-section {
  margin-bottom: 30px;

  .stat-card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
    }

    .stat-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;

      .stat-info {
        .stat-label {
          color: #7f8c8d;
          font-size: 0.9rem;
          margin-bottom: 8px;
          font-weight: 500;
        }

        .stat-value {
          font-size: 1.8rem;
          font-weight: bold;
          color: #2c3e50;
          margin: 0;
          line-height: 1;
        }
      }

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        color: white;

        &.icon-blue { background: linear-gradient(135deg, #3498db, #2980b9); }
        &.icon-green { background: linear-gradient(135deg, #2ecc71, #27ae60); }
        &.icon-orange { background: linear-gradient(135deg, #f39c12, #e67e22); }
        &.icon-purple { background: linear-gradient(135deg, #9b59b6, #8e44ad); }
      }
    }
  }
}

/* 提交列表 */
.submissions-table-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  .submission-info {
    .problem-title {
      margin: 0 0 4px 0;
      color: #2c3e50;
      font-size: 1rem;
      font-weight: 600;
    }

    .homework-title {
      margin: 0 0 8px 0;
      color: #7f8c8d;
      font-size: 0.85rem;
    }

    .submission-meta {
      display: flex;
      align-items: center;
      gap: 8px;

      .submit-time {
        color: #95a5a6;
        font-size: 0.8rem;
      }
    }
  }

  .status-info {
    .score-info {
      margin-top: 4px;

      .score {
        color: #e74c3c;
        font-weight: 600;
        font-size: 0.9rem;
      }
    }
  }

  .execution-info {
    .execution-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 2px;

      .label {
        color: #7f8c8d;
        font-size: 0.8rem;
      }

      .value {
        color: #2c3e50;
        font-weight: 500;
        font-size: 0.8rem;
      }
    }
  }
}

/* 提交详情对话框 */
.submission-detail {
  .detail-card {
    margin-bottom: 20px;
    border-radius: 12px;
    border: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    &.error-card {
      border-left: 4px solid #e74c3c;
    }

    .detail-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .label {
        color: #7f8c8d;
        font-weight: 500;
        min-width: 80px;
        margin-right: 10px;
      }

      .value {
        color: #2c3e50;
        font-weight: 500;

        &.score {
          color: #e74c3c;
          font-weight: 600;
        }
      }
    }

    .execution-detail {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid #ecf0f1;

      .label {
        color: #7f8c8d;
        font-weight: 500;
      }

      .value {
        color: #2c3e50;
        font-weight: 600;
      }
    }

    .error-content {
      margin: 0;
      color: #e74c3c;
      font-family: 'Courier New', monospace;
      font-size: 0.9rem;
      white-space: pre-wrap;
      word-break: break-all;
      background-color: #fdf2f2;
      padding: 15px;
      border-radius: 8px;
      border: 1px solid #fecaca;
    }

    .test-results {
      .test-result-item {
        margin-bottom: 15px;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        overflow: hidden;

        &.AC {
          border-color: #10b981;
          background-color: #f0fdf4;
        }

        &.WA {
          border-color: #ef4444;
          background-color: #fef2f2;
        }

        &.TLE {
          border-color: #f59e0b;
          background-color: #fffbeb;
        }

        &.RE,
        &.CE {
          border-color: #ef4444;
          background-color: #fef2f2;
        }

        .test-result-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 15px;
          background-color: #f8f9fa;
          border-bottom: 1px solid #e9ecef;
          font-weight: 600;
          color: #2c3e50;
        }

        .test-result-content {
          padding: 15px;

          .input-output {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;

            .input,
            .expected,
            .actual {
              strong {
                display: block;
                margin-bottom: 5px;
                color: #2c3e50;
              }

              pre {
                background-color: #f8f9fa;
                padding: 10px;
                border-radius: 4px;
                margin: 0;
                font-family: 'Courier New', monospace;
                font-size: 0.9rem;
                color: #2c3e50;
                white-space: pre-wrap;
                word-break: break-all;
                max-height: 100px;
                overflow-y: auto;
              }
            }
          }
        }
      }
    }

    .code-display {
      .code-content {
        margin: 0;
        background-color: #f8f9fa;
        padding: 15px;
        border-radius: 8px;
        font-family: 'Courier New', monospace;
        font-size: 0.9rem;
        color: #2c3e50;
        white-space: pre-wrap;
        word-break: break-all;
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #e9ecef;
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .submissions-page {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;

    .header-left {
      text-align: center;
    }

    .header-right {
      display: flex;
      justify-content: center;
    }
  }

  .filter-section {
    .el-row {
      .el-col {
        margin-bottom: 15px;
      }
    }
  }

  .stats-section {
    .el-col {
      margin-bottom: 20px;
    }
  }

  .submission-info {
    .submission-meta {
      flex-direction: column;
      align-items: flex-start;
      gap: 5px;
    }
  }

  .submission-detail {
    .detail-card {
      .test-results {
        .test-result-item {
          .test-result-content {
            .input-output {
              grid-template-columns: 1fr;
              gap: 10px;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .page-header {
    .header-left {
      h2 {
        font-size: 1.5rem;
      }
    }
  }

  .stat-card {
    .stat-content {
      padding: 15px;

      .stat-info {
        .stat-value {
          font-size: 1.5rem;
        }
      }

      .stat-icon {
        width: 40px;
        height: 40px;
        font-size: 1.2rem;
      }
    }
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}
</style>
